package com.hxx.day4.service.impl;

import com.hxx.day4.domain.User;
import com.hxx.day4.service.UserService;

public class UserServiceImpl implements UserService {

    //使用数组模拟数据库
    private User[] users = new User[3];
    @Override
    public void save(User user) {
        for (int index = 0; index < users.length; index++) {
            if (users[index] == null){
                users[index] = user;
                System.out.println("保存成功");
                return;
            }
        }
        System.out.println("数据库已满");
    }

    @Override
    public void update(User user) {
        //调用findById方法
        int index = findById(user.getId());
        if (index != -1){
            users[index].setAge(user.getAge());
            users[index].setName(user.getName());
            users[index].setSex(user.getSex());
            System.out.println("修改成功");
        }else {
            System.out.println("用户不存在");
        }
    }

    @Override
    public void delete(Integer id) {
        int index = findById(id);
        if (index != -1){
            users[index] = null;
            System.out.println("删除成功");
        }else {
            System.out.println("用户不存在");
        }

    }

    @Override
    public int findById(Integer id) {
        for (int index = 0; index < users.length; index++) {
            User user = users[index];
            //判断
            if (user != null && user.getId().equals(id)){
                return index;
            }
        }
        return -1;
    }

    @Override
    public User[] findAll() {
        return users;
    }
}
